//
//  SmileHttpTool.m
//  chengguaApp
//
//  Created by 微笑吧阳光 on 2018/4/4.
//  Copyright © 2018年 SmileFans. All rights reserved.
//

#import "SmileHttpTool.h"
#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"
#import "SmileHTTPSessionManager.h"
#import "SmileNetWorkState.h"
#import "YINetWorkAPIGenerate.h"
#import "sys/utsname.h"
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

#define KNetStatus @"status"
#define KNetData @"result"
#define KNetMsg @"message"

#import "NSString+handle.h"

@interface SmileHttpTool ()

/**注释---200成功 204 成功没有数据 code message */
@property (nonatomic, strong) SmileHTTPSessionManager *manager;
@end
@implementation SmileHttpTool

- (SmileHTTPSessionManager *)manager {
    if (!_manager) {
        _manager = [SmileHTTPSessionManager shareManager];
    }
    return _manager;
}

//创建单例
+ (SmileHttpTool *) sharedInstance
{
    static  SmileHttpTool *sharedInstance = nil ;
    static  dispatch_once_t onceToken;
    dispatch_once (& onceToken, ^ {
        //初始化自己
        sharedInstance = [[self alloc] init];
        //实例化请求对象
        sharedInstance.manager = [SmileHTTPSessionManager shareManager];
    });
    return  sharedInstance;
}
#pragma mark - 单例模式请求API
#pragma mark - GET
- (void)GET:(NSString *)URLString
 parameters:(id)parameters
     origin:(BOOL)isOrigin
    success:(NetworkSuccessBlock)success
    failure:(NetworkFailureBlock)failure
{
    if (!kStringIsEmpty([[DJLoginHelper sharedInstance] cj_UserUuid])) {
        [self.manager.requestSerializer setValue:[[DJLoginHelper sharedInstance] cj_UserUuid] forHTTPHeaderField:@"userid"];
//         NSString  * order = [NSString stringWithFormat:@"%@order",MatchHOST_IP];
        
    }else{
         [self.manager.requestSerializer setValue:@"" forHTTPHeaderField:@"userid"];
    }
    
    [self.manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *errorData;
        NSString* strdata = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];//在将NSString类型转为NSD
        if (!kStringIsEmpty(strdata)) {
                  success(0,@"",[strdata URLDecodedString]);
        }
  
//        if (isOrigin) {
//            success(0,@"",responseDict);
//            return ;
//        }
//        NSInteger status = [responseDict[KNetStatus] integerValue];
//        NSString * msg = responseDict[KNetMsg];
//        id data = responseDict[KNetData];
//        if (success) {
//            success(status,msg,data);
//        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(nil, error);
        }
    }];
}

- (void)GET_Data:(NSString *)URLString
 parameters:(id)parameters
     origin:(BOOL)isOrigin
    success:(NetworkSuccessWithTaskBlock)success
    failure:(NetworkFailureBlock)failure
{
    if (!kStringIsEmpty([[DJLoginHelper sharedInstance] cj_UserUuid])) {
        [self.manager.requestSerializer setValue:[[DJLoginHelper sharedInstance] cj_UserUuid] forHTTPHeaderField:@"userid"];
    }else{
        [self.manager.requestSerializer setValue:@"" forHTTPHeaderField:@"userid"];
    }
    //  [self.manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"mobileType"];
    [self.manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        success(0,task,responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(nil, error);
        }
    }];
}

#pragma mark - POST
- (void)POST:(NSString *)URLString
  parameters:(id)parameters
      origin:(BOOL)isOrigin
     success:(NetworkSuccessBlock)success
     failure:(NetworkFailureBlock)failure
{
//    [self.manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [self.manager POST:URLString parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //NSLog(@"responseObjectresponseObjectresponseObjectresponseObjectresponseObjectresponseObject----%@",responseObject);
       // NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//       NSError *errorData;
//        NSString* strdata = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];//在将NSString类型转为NSData
//         NSData * data =[strdata dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
//        NSLog(@"responseObject---%@",dict);
//        NSDictionary *responseDict = [NSDictionary dictionaryWithDictionary:responseObject];
//        if (isOrigin) {
//            success(0,@"",responseDict);
//            return ;
//        }
//        //[responseDict[KNetStatus] integerValue];
//        NSInteger status = [responseObject jsonInteger:KNetStatus];
//        NSString * msg = responseDict[KNetMsg];
//        id data = responseDict[KNetData];
//        if (success) {
//            success(status,msg,data);
//        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            failure(nil, error);
        }
    }];
}





#pragma mark - 请求API
+ (void)httpWork_get:(NSString *)url parameters:(NSMutableDictionary *)parameters progress:(void (^)(NSProgress *))progress success:(void (^)(id))success successOther:(void (^)(id))successOther failure:(void (^)(NSError *))failure endRfresh:(void (^)(void))endRfresh showLoadingView:(BOOL)showLoadingView {
    
    if ([SmileNetWorkState checkNetWorkState].isRightNetwork == YES) {
        if (showLoadingView) {
            //加载动画
            
        }
        
        [[[SmileHttpTool alloc] init].manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            if (progress) {
                progress(uploadProgress);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (showLoadingView) {//隐藏动画
                
            }
            if (endRfresh) {
                endRfresh();
            }
            
            if (responseObject) {
            //NSLog(@"💗--responseObject--%@",responseObject);
                //具体看项目接口返回的层级
                NSInteger code = [[responseObject valueForKey:@"status"] integerValue];
                
                if (code == 200) {
                    
                    if (success) {
                        success(responseObject);
                    }
                    
                } else if (code == 100) {//比如全局统一的，直接在里面弹窗处理
                    
                } else {
                    
                    if (code == 204) {//需要弹窗提示充值
                        if (successOther) {
                            successOther(responseObject);
                        }
                    } else {
                        //提示吐司窗口
                    }
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (showLoadingView) {//隐藏动画
                
            }
            if (endRfresh) {
                endRfresh();
            }
            if (failure) {
                failure(error);
            }
        }];
    } else {
        //没有网络
    }
    
    
}

+ (void)httpWork_post:(NSString *)url parameters:(NSMutableDictionary *)parameters progress:(void (^)(NSProgress *))progress success:(void (^)(id))success successOther:(void (^)(id))successOther failure:(void (^)(NSError *))failure endRfresh:(void (^)(void))endRfresh showLoadingView:(BOOL)showLoadingView {
    
    
//    responseObject--{
//        message = "\U767b\U5f55\U5931\U8d25";
//        result = "";
//        status = 404;
//    }
    if ([SmileNetWorkState checkNetWorkState].isRightNetwork == YES) {
        if (showLoadingView) {
            //加载动画
        }
        
        [[[SmileHttpTool alloc] init].manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            if (progress) {
                progress(uploadProgress);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (showLoadingView) {//隐藏动画
                
            }
            if (endRfresh) {
                endRfresh();
            }
            
            if (responseObject) {
                //具体看项目接口返回的层级
                NSInteger code = [[responseObject valueForKey:@"status"] integerValue];
                
                if (code == 0) {
                    
                    if (success) {
                        success(responseObject);
                    }
                    
                } else if (code == 100) {//比如全局统一的，直接在里面弹窗处理
                    
                } else {
                    
                    if (code == 200) {//需要弹窗提示充值
                        if (successOther) {
                            successOther(responseObject);
                        }
                    } else {
                        //提示吐司窗口
                    }
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (showLoadingView) {//隐藏动画
                
            }
            if (endRfresh) {
                endRfresh();
            }
            if (failure) {
                failure(error);
            }
        }];
    } else {
        //没有网络
    }
}
///只需要管成功，并且一定需要加载动画
+ (void)httpWork_get:(NSString *)url parameters:(NSMutableDictionary *)parameters success:(void (^)(id responseObject))success {
    [self httpWork_get:url parameters:parameters progress:nil success:success successOther:nil failure:nil endRfresh:nil showLoadingView:YES];
}
///需要加载动画，还要判断code为其他状态
+ (void)httpWork_get:(NSString *)url parameters:(NSMutableDictionary *)parameters success:(void (^)(id responseObject))success successOther:(void (^)(id responseObject))successOther {
    [self httpWork_get:url parameters:parameters progress:nil success:success successOther:successOther failure:nil endRfresh:nil showLoadingView:YES];
}
///有上啦加载下拉刷新的情况，
+ (void)httpWork_get:(NSString *)url parameters:(NSMutableDictionary *)parameters success:(void (^)(id responseObject))success successOther:(void (^)(id responseObject))successOther failure:(void (^)(NSError *error))failure endRfresh:(void (^)(void))endRfresh  showLoadingView:(BOOL)showLoadingView {
    [self httpWork_get:url parameters:parameters progress:nil success:success successOther:successOther failure:failure endRfresh:endRfresh showLoadingView:showLoadingView];
}


- (void)httpWork_get:(NSString *)url parameters:(NSMutableDictionary *)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
    
    if ([SmileNetWorkState checkNetWorkState].isRightNetwork == YES) {
        
        [[[SmileHttpTool alloc] init].manager POST:url parameters:[self setCommonRequestParmas:parameters isEncrypt:0]  progress:^(NSProgress * _Nonnull uploadProgress) {

        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (responseObject) {
                NSLog(@"💗--responseObject--%@",responseObject);
                //具体看项目接口返回的层级
                NSInteger code = [[responseObject valueForKey:@"status"] integerValue];
                
                if (code == 200) {
                    
                    if (success) {
                        success(responseObject);
                    }
                    
                } else if (code == 100) {//比如全局统一的，直接在里面弹窗处理
                    
                } else {
                    
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            if (failure) {
                failure(error);
            }
        }];
        
        
    } else {
        //没有网络
        
        
    }
    
}

#pragma mark - 自定义请求参数
//设置公共请求参数
-(id)setCommonRequestParmas:(id)parmas isEncrypt:(NSInteger)isEncrypt{
    
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:parmas];
    
    //Authorization  token值
//    NSString *token= [GDLoginUser authToken];
//    if (!kStringIsEmpty(token)) {
//        [param setValue:token forKey:@"token"];
//    }else{
//        [param setValue:@"" forKey:@"token"];
//    }
//    [param setValue:@(0) forKey:@"appKey"];
    [param setValue:[self dictionaryToJson:[self getDeviceStatue]] forKey:@"devicStatue"];
    [param setValue:@(isEncrypt) forKey:@"isEncrypt"];
    [param setValue:CurrentVersionNum forKey:@"apiVersion"];
    NSLog(@"设置公共请求参数------%@",param);
    return param;
}

- (NSString*)deviceVersion{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString * deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    //iPhone
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([deviceString isEqualToString:@"iPhone8,4"])    return@"iPhone SE";
    if ([deviceString isEqualToString:@"iPhone9,1"])    return@"iPhone 7";
    if ([deviceString isEqualToString:@"iPhone9,2"])    return@"iPhone 7 Plus";
    if ([deviceString isEqualToString:@"iPhone10,1"])   return@"iPhone 8";
    if ([deviceString isEqualToString:@"iPhone10,4"])   return@"iPhone 8";
    if ([deviceString isEqualToString:@"iPhone10,2"])   return@"iPhone 8 Plus";
    if ([deviceString isEqualToString:@"iPhone10,5"])   return@"iPhone 8 Plus";
    if ([deviceString isEqualToString:@"iPhone10,3"])   return@"iPhone X";
    if ([deviceString isEqualToString:@"iPhone10,6"])   return@"iPhone X";
    return deviceString;
}
//字典转换成字符串
- (NSString*)dictionaryToJson:(NSDictionary *)dic{
    if (!dic) {
        return @"";
    }
    return [[NSString alloc] initWithData:[self dictionaryToData:dic] encoding:NSUTF8StringEncoding];
}
-(NSData*)dictionaryToData:(NSDictionary *)dic{
    if (!dic) {
        return [NSData data];
    }
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return jsonData;
}
-(NSDictionary *)getDeviceStatue{
    NSMutableDictionary * deviceStatue = [NSMutableDictionary dictionaryWithCapacity:0];
    /*
     dt    String    机型
     nt    String    网络类型
     packageName    String    包名
     devicesId    String    手机设备Id
     imei    String    手机唯一码
     terminalType    String    1:ios 2:android
     sv    String    系统版本
     mac    String    mac地址
     vc    String    apk版本号
     imsi    String    手机卡识别码
     vn    String    apk版本名
     sid    String    平台设备码，由服务器端生成
     cpu    String    cpu
     channelId    String    渠道号接口返回码对应信息
     areaName    String    地区信息
     */
    [deviceStatue setValue:[self deviceVersion] forKey:@"dt"];
    [deviceStatue setValue:@"wifi" forKey:@"nt"];
    [deviceStatue setValue:BundleId forKey:@"packageName"];
    [deviceStatue setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forKey:@"devicesId"];
    [deviceStatue setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forKey:@"imei"];
    [deviceStatue setValue:@"1" forKey:@"terminalType"];
    [deviceStatue setValue:[[UIDevice currentDevice] systemVersion] forKey:@"sv"];
    [deviceStatue setValue:CurrentVersionNum forKey:@"vc"];
    [deviceStatue setValue:[self macAddress] forKey:@"mac"];
    [deviceStatue setValue:@"" forKey:@"imsi"];
    [deviceStatue setValue:CurrentVersion forKey:@"vn"];
    [deviceStatue setValue:@"" forKey:@"sid"];
    [deviceStatue setValue:@"" forKey:@"cpu"];
    [deviceStatue setValue:@"" forKey:@"channelId"];
    [deviceStatue setValue:@"" forKey:@"areaName"];
    
    return deviceStatue;
}
//获取Mac地址
- (NSString *)macAddress
{
    
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error/n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1/n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!/n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    
    NSLog(@"outString:%@", outstring);
    
    free(buf);
    
    return [outstring uppercaseString];
}


#pragma mark - 校验图形验证码
- (void)GET_DataDChackImageCode:(NSString *)URLString
                       imageKey:(NSString *)imageKey
                     parameters:(id)parameters
                         origin:(BOOL)isOrigin
                        success:(NetworkSuccessWithTaskBlock)success
                        failure:(NetworkFailureBlock)failure{
    [self.manager.requestSerializer setValue:imageKey forHTTPHeaderField:@"cpkey"];
    [self.manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(0,task,responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(nil, error);
        }
    }];
    
    
    
    
}
#pragma mark - 获取order
- (void)GET_DataorderCode:(NSString *)URLString
                       token:(NSString *)token
                     parameters:(id)parameters
                         origin:(BOOL)isOrigin
                        success:(NetworkSuccessWithTaskBlock)success
                        failure:(NetworkFailureBlock)failure{
//    [self.manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    NSString *tokenstr = [NSString stringWithFormat:@"Bearer %@",token];
    [ self.manager.requestSerializer setValue:tokenstr forHTTPHeaderField:@"Authorization"];
    [self.manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(0,task,responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(nil, error);
        }
    }];
    
    
    
    
}


@end
